package edu.xpu.project.user.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.xpu.project.user.entity.ProjectUser;
import edu.xpu.project.user.repository.ProjectUserRepository;

/**
 * @describe 人员业务操作的实现类
 * @author liukang
 * @date 2017年4月18日
 */
@Transactional(readOnly=true)
@Service
public class ProjectUserServiceImpl implements ProjectUserService {
	
	@Autowired
	private ProjectUserRepository projectUserRepository;
	
	@Override
	public Page<ProjectUser> getPageByCriterias(String pageNumberStr,
			String pageSizeStr, final ProjectUser projectUser) {
		Integer pageNumber = 1;
		Integer pageSize = 10;
		try {
			pageNumber = Integer.parseInt(pageNumberStr);
		} catch (Exception e) {}
		try {
			pageSize = Integer.parseInt(pageSizeStr);
		} catch (Exception e) {}
		Pageable pageable = new PageRequest(pageNumber - 1, pageSize, new Sort(Direction.DESC, "createDate"));
		
		return projectUserRepository.findAll(new Specification<ProjectUser>() {
			@Override
			public Predicate toPredicate(Root<ProjectUser> root, CriteriaQuery<?> query,
					CriteriaBuilder builder) {
				if (projectUser == null) {
					return null;
				}
				//添加用户的查询条件
				List<Predicate> predicates = new ArrayList<Predicate>(3);
				predicates.add(builder.equal(root.get("userType").as(Integer.class), projectUser.getUserType()));
				
				if (predicates.size() == 0) {
					return null;
				}
				Predicate[] predArr= new Predicate[predicates.size()];
				return builder.and(predicates.toArray(predArr));
			}
		}, pageable);
	}
	
	@Transactional(readOnly=false)
	@Override
	public ProjectUser saveOrUpdate(ProjectUser t) {
		return projectUserRepository.saveAndFlush(t);
	}

	@Transactional(readOnly=false)
	@Override
	public void delete(Long id) {
		projectUserRepository.delete(id);
	}

	@Override
	public ProjectUser get(Long id) {
		return projectUserRepository.findOne(id);
	}

	@Override
	public ProjectUser userLogin(String username, String pwd) {
		List<ProjectUser> userLogin = projectUserRepository.userLogin(username, pwd);
		if (userLogin != null && userLogin.size() != 0) {
			return userLogin.get(0);
		}
		return null;
	}

	@Override
	public ProjectUser findByExamineeNumber(String examineeNumber) {
		return projectUserRepository.findByExamineeNumber(examineeNumber);
	}


}
